package com.qujia.station.service.impl;

import com.github.pagehelper.PageHelper;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.Commodity;
import com.qujia.station.domain.CommodityManagement;
import com.qujia.station.domain.NonOilCategory;
import com.qujia.station.mapper.CommodityManagementMapper;
import com.qujia.station.mapper.CommodityMapper;
import com.qujia.station.service.CommodityManagementService;
import com.qujia.station.service.CommodityService;
import com.qujia.station.service.INonOilCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (Commodity)表服务实现类
 *
 * @author makejava
 * @since 2023-08-15 14:11:35
 */
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityMapper commodityMapper;
    @Resource
    private CommodityManagementMapper commodityManagementMapper;

    @Autowired
    private INonOilCategoryService nonOilCategoryService;
    @Autowired
    private CommodityManagementService commodityManagementService;
    /**
     * 通过ID查询单条数据
     *
     * @param commodityId 主键
     * @return 实例对象
     */
    @Override
    public Commodity queryById(Long commodityId) {
        return this.commodityMapper.queryById(commodityId);
    }

    /**
     * 分页查询
     *
     * @param commodity 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Commodity> queryByPage(Commodity commodity, PageRequest pageRequest) {
        long total = this.commodityMapper.count(commodity);
        return new PageImpl<>(this.commodityMapper.queryAllByLimit(commodity, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity insert(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setCreateUser(currentUser.getUser().getUserId());
        commodity.setCreateTime(new Date());
        this.commodityMapper.insert(commodity);
        return commodity;
    }

    /**
     * 修改数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity update(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setUpdateTime(new Date());
        commodity.setUpdateUser(currentUser.getUser().getUserId());
        this.commodityMapper.update(commodity);
        return this.queryById(commodity.getCommodityId());
    }

    /**
     * 通过主键删除数据
     *
     * @param commodityId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long commodityId) {
        return this.commodityMapper.deleteById(commodityId) > 0;
    }

    @Override
    public int delete(List<Long> ids) {
        if(ids!=null&&ids.size()>0){
            return commodityMapper.deleteByIds(ids);
        }
        return 0;
    }

    @Override
    @Transactional
    public Integer putAway(Commodity commodity) {
        Commodity commodity2 = commodityMapper.queryById(commodity.getCommodityId());
        if(commodity.getPutawayNum()==null){
            commodity.setPutawayNum(0);
        }
        if(commodity2.getInventory()<commodity.getPutawayNum()){
            throw new CustomException("上架数量超过库存");
        }

        CommodityManagement commodityManagement=new CommodityManagement();
        commodityManagement.setCommodityId(commodity.getCommodityId());
        commodityManagement.setStationId(commodity.getStationId());
        List<CommodityManagement> query = commodityManagementMapper.query(commodityManagement);
        if(query.size()>0){
            //如果之前已经上架过了,更新库存(旧库存加上上架数量)和状态
            commodityManagement=query.get(0);
            commodityManagement.setPutawayTime(new Date());
            commodityManagement.setStatus(CommodityManagement.ON_SALE);
            commodityManagement.setInventory(commodityManagement.getInventory()+commodity.getPutawayNum());
            if(commodity.getSalePrice()!=null){
                commodityManagement.setSalePrice(commodity.getSalePrice());
            }
            commodityManagementService.update(commodityManagement);
            //更新商品列表库存
            commodity2.setInventory(commodity2.getInventory()-commodity.getPutawayNum());
            commodityMapper.update(commodity2);
        }else{
            //如果之前没上架过，新增
            commodityManagement.setPutawayTime(new Date());
            commodityManagement.setCommodityName(commodity2.getCommodityName());
            if(commodity.getSalePrice()!=null){
                commodityManagement.setSalePrice(commodity.getSalePrice());
            }else{
                commodityManagement.setSalePrice(commodity2.getSalePrice());
            }
            commodityManagement.setRetailPrice(commodity2.getRetailPrice());
            //新增商品管理库存等于商品上架库存
            commodityManagement.setInventory(commodity.getPutawayNum());
            commodityManagement.setStatus(CommodityManagement.ON_SALE);

            //更新商品列表库存
            commodity2.setInventory(commodity2.getInventory()-commodity.getPutawayNum());
            commodityMapper.update(commodity2);
            //商品管理新增数据
            commodityManagementService.insert(commodityManagement);
        }
        return 0;
    }

    @Override
    public List<Commodity> query(Commodity commodity) {
        Long categoryId = commodity.getCategoryId();
        if(categoryId!=null){
            List<Long> childIds = nonOilCategoryService.getChildIds(categoryId);
            childIds.add(categoryId);
            commodity.setCategoryIds(childIds);
        }
        PageHelper.startPage(commodity.getPageNum(), commodity.getPageSize(), commodity.getOrderBy());
        List<Commodity> query = commodityMapper.query(commodity);
        PageHelper.clearPage();
        List<NonOilCategory> list = nonOilCategoryService.selectAll();

        for (Commodity c : query) {
           c.setCategoryName(nonOilCategoryService.queryCategoryName(c.getCategoryId(),list));
        }
        return query;
    }
}
